package com.hayden.fileMonitor.util;

import com.hayden.fileMonitor.MonitoringService;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class MyService {
    private ExecutorService executorService;
    private static final Logger LOGGER = LoggerFactory.getLogger(MyService.class);

    public MyService() {
        // 创建一个大小为10的线程池
        executorService = Executors.newFixedThreadPool(10);
    }

    public void service(String path) {
        executorService.execute(new ServiceTask(path));
    }

    private class ServiceTask implements Runnable {
        private String path;
        public ServiceTask(String path) {
            this.path = path;
        }

        public void run() {
            System.out.println("service starting...");
            //目录
            File directory = new File(path);
            LOGGER.info("监控目录为：{}",path);
            //观察者
            FileAlterationObserver observer = new FileAlterationObserver(directory);
            //监听器
            observer.addListener(new MonitoringService.MyFileAlterationListener());
            ConfigFileReader reader = new ConfigFileReader();
            String time = reader.getProperty("monitor.interval");
            long interval = Long.parseLong(time);//观察频率
            LOGGER.info("观察频率为：{}ms",time);
            //监控器
            FileAlterationMonitor monitor = new FileAlterationMonitor(interval);
            monitor.addObserver(observer);
            try {
                monitor.start();
            } catch (Exception e) {
                LOGGER.error("监控开启失败：",e);
            }
        }
    }
}